package com.firewolf.mains;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.entities.Customer;

public class MainDriver {
	
	private EntityManagerFactory factory = null;
	private EntityManager manager = null;
	private EntityTransaction tx = null;
	
	@Before
	public void init(){
		factory = Persistence.createEntityManagerFactory("jpa");
		manager = factory.createEntityManager();
		tx = manager.getTransaction();
		tx.begin();
	}
	
	@After
	public void destory(){
		tx.commit();
		manager.close();
		factory.close();
	}
	
	/**
	 * persist ： 新增，如果给对象设置了id，则抛出异常
	 */
	@Test
	public void add(){
		Customer c = new Customer();
		c.setAge(14);
		c.setBirthday(new Date());
//		c.setId(2);
		c.setName("zhihui");
		manager.persist(c);
	}
	
	/**
	 * find：根据ID查询，立即加载
	 *  先打印查询语句，再打印"xxx"
	 *  没有对应记录返回null
	 */
	@Test
	public void find(){
		Customer customer = manager.find(Customer.class, 4);
		System.out.println("xxx");
		System.out.println(customer);
	}
	/**
	 * getReference : 根据ID查询，懒加载
	 * 如果id在数据库中没有对应的记录，则抛出异常
	 */
	@Test
	public void getRefence(){
		Customer customer = manager.getReference(Customer.class, 4);
		System.out.println("xxx");
		System.out.println(customer);
	}
	
	/**
	 * merge:修改或者新增
	 * 其实对于修改，不用调用任何方法，直接set属性之后，就会自动的修改
	 * 如果id在数据库中存在，则修改，否则新增
	 */
	@Test
	public void merge(){
//		Customer c = new Customer();
//		c.setAge(14);
//		c.setBirthday(new Date());
//		c.setId(2);
//		c.setName("zhangsan2");
//		manager.merge(c);
		
		Customer c2 =manager.find(Customer.class, 2);
		c2.setName("lisi");
	}
	
	/**
	 * remove : 删除
	 * 删除的对象必须是从数据库查询出来的
	 */
	@Test
	public void delete(){
		//这种方式获取到的对象删除不了，会报异常
//		Customer c = new Customer();
//		c.setId(2);
		Customer c = manager.getReference(Customer.class, 1);
		manager.remove(c);
	}
}
